import { createRouter, createWebHashHistory } from 'vue-router'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'
import tools from '@/utils/tools'

const initMeta = {
  isHeader: true,
  isFooter: true,
  isLogin: false,
  isNav: false
}

const routes = [
  {
    path: '/',
    redirect: '/home'
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('@/view/home/index.vue'),
    meta: {
      title: '网站首页',
      isNav: true
    }
  },
  {
    path: '/works',
    name: 'Works',
    component: () => import('@/view/works/index.vue'),
    meta: {
      title: '作品展区',
      isNav: true
    }
  },
  {
    path: '/blog',
    name: 'blog',
    component: () => import('@/view/blog/index.vue'),
    meta: {
      title: '日志博客',
      isNav: true
    }
  },
  {
    path: '/nav',
    name: 'Nav',
    component: () => import('@/view/nav/index.vue'),
    meta: {
      title: '常用导航',
      isNav: true
    }
  },
  {
    path: '/vscode',
    name: 'Vscode',
    component: () => import('@/view/vscode/index.vue'),
    meta: {
      title: 'Vscode插件',
      isNav: true
    }
  },
  {
    path: '/about',
    name: 'About',
    component: () => import('@/view/about/index.vue'),
    meta: {
      title: '关于自己',
      isNav: true
    }
  },
  {
    path: '/demo',
    name: 'Demo',
    component: () => import('@/view/demo/index.vue'),
    meta: {
      title: 'demo'
    }
  },
  {
    path: '/weather',
    name: 'Weather',
    component: () => import('@/view/weather/index.vue'),
    meta: {
      title: '天气'
    }
  },
  {
    path: '/effect',
    name: 'Effect',
    component: () => import('@/view/effect/index.vue'),
    meta: {
      title: '特效一'
    }
  },
  {
    path: '/404',
    name: 'Page404',
    hidden: true,
    component: () => import('@/view/404/index.vue'),
    meta: {
      isHeader: false,
      title: '我迷路了'
    }
  },
  {
    path: '/:pathMatch(.*)',
    redirect: '/404'
  }
]
routes.forEach((item) => {
  item.meta = { ...initMeta, ...item.meta }
})
const router = createRouter({
  history: createWebHashHistory(),
  linkActiveClass: 'active',
  routes,
  scrollBehavior(to, from, savedPosition) {
    if (savedPosition) {
      return savedPosition
    } else {
      return { top: 0 }
    }
  }
})

// 前置路由
router.beforeEach(async (to, from, next) => {
  NProgress.start()
  document.title = tools.setPageTitle(to.meta.title)

  next()
})

// 后置路由
router.afterEach(() => {
  NProgress.done()
})

export default router
